package com.example.chapter08;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.chapter08.database.ShoppingDBHelper;
import com.example.chapter08.entity.GoodsInfo;
import com.example.chapter08.util.ToastUtil;


public class ShoppingDetailActivity extends AppCompatActivity implements View.OnClickListener {

    private ShoppingDBHelper mDBHelper;
    private TextView tv_title, tv_count, tv_goods_price, tv_goods_desc;
    private ImageView iv_goods_pic;
    private int mGoodsId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_detail);

        tv_title = findViewById(R.id.tv_title);   // title_shopping.xml
        tv_count = findViewById(R.id.tv_count);
        tv_goods_price = findViewById(R.id.tv_goods_price);  // activity_shopping_detail.xml
        tv_goods_desc = findViewById(R.id.tv_goods_desc);
        iv_goods_pic = findViewById(R.id.iv_goods_pic);

        findViewById(R.id.iv_back).setOnClickListener(this);    // title_shopping.xml
        findViewById(R.id.iv_cart).setOnClickListener(this);
        findViewById(R.id.btn_add_cart).setOnClickListener(this);  // activity_shopping_detail.xml

        tv_count.setText(String.valueOf(MyApplication.getInstance().goodsCount));

        mDBHelper = ShoppingDBHelper.getInstance(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        showDetail();
    }

    private void showDetail() {
        mGoodsId = getIntent().getIntExtra("goods_id", 0);
        if (mGoodsId > 0) {
            GoodsInfo goodsInfo = mDBHelper.queryGoodsInfoById(mGoodsId);
            tv_title.setText(goodsInfo.name);
            tv_goods_price.setText("￥" + String.valueOf(goodsInfo.price));
            tv_goods_desc.setText(goodsInfo.description);
            iv_goods_pic.setImageURI(Uri.parse(goodsInfo.picPath));
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_back) {
            finish();
        } else if (v.getId() == R.id.iv_cart) {
            Intent intent = new Intent(ShoppingDetailActivity.this, ShoppingCartActivity.class);
            startActivity(intent);
        } else if (v.getId() == R.id.btn_add_cart) {
            addToCart(mGoodsId);
        }
    }

    private void addToCart(int goodsId) {
        int goodsCount = ++MyApplication.getInstance().goodsCount;
        tv_count.setText(String.valueOf(goodsCount));
        mDBHelper.insertCartInfo(goodsId);
        ToastUtil.show(this, "成功添加到购物车");
    }
}